package com.nbjtjc.safe.service.danger;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nbjtjc.safe.annotation.DataFilter;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.danger.DangerInspectListMapper;
import com.nbjtjc.safe.mapper.danger.DangerInspectMapper;
import com.nbjtjc.safe.mapper.danger.DangerInspectTableLabelMapper;
import com.nbjtjc.safe.mapper.danger.SafeDangerInspectLabelMapper;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.mapper.sys.SysPostMapper;
import com.nbjtjc.safe.model.danger.DangerInspect;
import com.nbjtjc.safe.model.danger.DangerInspectList;
import com.nbjtjc.safe.model.danger.DangerInspectTableLabel;
import com.nbjtjc.safe.model.danger.SafeDangerInspectLabel;
import com.nbjtjc.safe.model.know.SafeKnowLabel;
import com.nbjtjc.safe.model.know.SafeKnowledge;
import com.nbjtjc.safe.model.sys.SysDept;
import com.nbjtjc.safe.model.sys.SysPost;
import com.nbjtjc.safe.util.FileUtil;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @auther guqianbin
 * @date 2018/4/9 10:12
 **/
@Service
public class DangerInspectService {

    private static Logger logger = LoggerFactory.getLogger(DangerInspectService.class);
    @Autowired
    private DangerInspectMapper dangerInspectMapper;
    @Autowired
    private DangerInspectListMapper dangerInspectListMapper;

    @Autowired
    private SafeDangerInspectLabelMapper safeDangerInspectLabelMapper;
    @Autowired
    private DangerInspectTableLabelMapper dangerInspectTableLabelMapper;
    @Autowired
    private FileUtil fileUtil;
    @Autowired
    private SysPostMapper sysPostMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    /**
     * 收藏检查表
     *
     * @param dangerInspect
     * @return
     */
    @Transactional
    public Result collectionTable(DangerInspect dangerInspect) {
        Result result = new Result();

        List<DangerInspect> fromDangerInspects = dangerInspectMapper.searchWithList(dangerInspect, new ArrayList<>());
        List<DangerInspect> toDangerInspects = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fromDangerInspects)) {
            fromDangerInspects.forEach(fromTable -> {
                DangerInspect dangerTable = new DangerInspect();
                dangerTable.setCompanyId(MyShiroUtils.getCompanyId());
                dangerTable.setName(fromTable.getName());
                dangerTable.setExplain(fromTable.getExplain());
                dangerTable.setCreateTime(new Date());
                dangerTable.setCreateUserId(MyShiroUtils.getSessionUserId());
                dangerTable.setDeptId(MyShiroUtils.getDeptId());
                dangerTable.setFromTableId(fromTable.getId());
                dangerTable.setTableType(0);
                toDangerInspects.add(dangerTable);
                copyTableList(fromTable, dangerTable, MyShiroUtils.getCompanyId());
            });
        }
        dangerInspectMapper.insertList(toDangerInspects);
        insertTableList(toDangerInspects);
        //复制标签
        copyTableLabels(fromDangerInspects, toDangerInspects);
        return result;
    }


    public Result getSelfInspectId() {
        Result result = new Result();
        SysDept dept = sysDeptMapper.selectByPrimaryKey(MyShiroUtils.getDeptId());
        SysDept company = sysDeptMapper.selectByPrimaryKey(MyShiroUtils.getCompanyId());
        SysPost post = sysPostMapper.selectByPrimaryKey(MyShiroUtils.getPostId());
        result.setData(0);
        if (ObjectUtil.isNotNull(company) && ObjectUtil.isNotNull(company.getSelfInspectId())) {
            if (!company.getSelfInspectId().equals(0)) {
                result.setData(company.getSelfInspectId());
            }
        }
        if (ObjectUtil.isNotNull(dept) && ObjectUtil.isNotNull(dept.getSelfInspectId())) {
            if (!dept.getSelfInspectId().equals(0)) {
                result.setData(dept.getSelfInspectId());
            }
        }
        if (ObjectUtil.isNotNull(post) && ObjectUtil.isNotNull(post.getSelfInspectId())) {
            if (!dept.getSelfInspectId().equals(0)) {
                result.setData(dept.getSelfInspectId());
            }
        }
        if (result.getData().equals(0)) {
            result.setFalse("系统没有自查表，或者部门、公司、岗位都没有设置过对应的岗位自查表");
        }
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result add(DangerInspect dangerInspect) {
        Result result = new Result();
        dangerInspect.setCreateTime(new Date());
        dangerInspect.setCreateUserId(MyShiroUtils.getSessionUserId());
        dangerInspect.setDeptId(MyShiroUtils.getDeptId());
        int res = dangerInspectMapper.insertSelective(dangerInspect);
        if (res != 1) {
            result.setFalse("添加失败");
            return result;
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getDangerInspectLists())) {
            insertInspectList(dangerInspect);
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getSafeDangerInspectLabels())) {
            insertInspectLabels(dangerInspect);
        }
        result.setData(dangerInspect);
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result delete(DangerInspect dangerInspect) {
        Result result = new Result();
        dangerInspectMapper.deleteByPrimaryKey(dangerInspect);
        dangerInspectListMapper.deleteByInspectId(dangerInspect.getId());
        safeDangerInspectLabelMapper.deleteByInspectId(dangerInspect.getId());
        return result;
    }

    @Transactional(rollbackFor = Throwable.class)
    public Result update(DangerInspect dangerInspect) {
        Result result = new Result();
        dangerInspectMapper.updateByPrimaryKeySelective(dangerInspect);
        safeDangerInspectLabelMapper.deleteByInspectId(dangerInspect.getId());
        dangerInspectListMapper.deleteByInspectId(dangerInspect.getId());
        if (CollectionUtil.isNotEmpty(dangerInspect.getSafeDangerInspectLabels())) {
            insertInspectLabels(dangerInspect);
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getDangerInspectLists())) {
            insertInspectList(dangerInspect);
        }
        return result;
    }


    /**
     * @param filterSql 放sql拦截的语句
     * @param label
     * @return
     */
    @DataFilter(tableAlias = "danger_inspect")
    public Result find(String filterSql, SafeDangerInspectLabel label) {
        Result result = new Result();
        if (CollectionUtil.isNotEmpty(label.getLabels())) {
            result.setData(searchByLabels(label, filterSql));
        } else {
            PageHelper.startPage(label.getPageCurrent(), label.getPageSize());
            List<DangerInspect> dangerInspects = dangerInspectMapper.search(label.getDangerInspect(), null, filterSql);
            result.setData(new PageInfo<>(dangerInspects));
        }
        return result;
    }

    /**
     * 按公司复制检查表,复制该公司的所有检查表，0表示系统的检查表
     *
     * @return
     */
    @Transactional
    public boolean copyInspectTableByCompany(int fromCompanyId, int toCompanyId) {
        DangerInspect dangerInspect = new DangerInspect();
        dangerInspect.setCompanyId(fromCompanyId);
        List<DangerInspect> fromDangerInspects = dangerInspectMapper.searchWithList(dangerInspect, new ArrayList<>());
        List<DangerInspect> toDangerInspects = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fromDangerInspects)) {
            fromDangerInspects.forEach(fromTable -> {
                DangerInspect dangerTable = new DangerInspect();
                dangerTable.setCompanyId(toCompanyId);
                dangerTable.setName(fromTable.getName());
                dangerTable.setExplain(fromTable.getExplain());
                dangerTable.setCreateTime(new Date());
                dangerTable.setCreateUserId(MyShiroUtils.getSessionUserId());
                dangerTable.setDeptId(MyShiroUtils.getDeptId());
                dangerTable.setFromTableId(fromTable.getId());
                toDangerInspects.add(dangerTable);
                copyTableList(fromTable, dangerTable, toCompanyId);
            });
        }
        dangerInspectMapper.insertList(toDangerInspects);
        insertTableList(toDangerInspects);
        //复制标签
        copyTableLabels(fromDangerInspects, toDangerInspects);
        return true;
    }


    /**
     * 导入隐患检查表
     *
     * @param file
     * @param dangerInspect
     * @return
     */
    public Result importDangerInspect(File file, DangerInspect dangerInspect) throws IOException {
        Result result = new Result();
        if (file.getName().endsWith("xls")) {
            dangerInspect.setName(file.getName().replace(".xls", ""));
            readXls(file, dangerInspect);
        } else if (file.getName().endsWith("xlsx")) {
            dangerInspect.setName(file.getName().replace(".xlsx", ""));
            readXlsx(file, dangerInspect);
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getImportLabelIds())) {
            dangerInspect.setTableLabelId(dangerInspect.getImportLabelIds()
                    .get(dangerInspect.getImportLabelIds().size() - 1));
        }
        dangerInspect.setCompanyId(MyShiroUtils.getCompanyId());
        dangerInspect.setCreateTime(new Date());
        dangerInspect.setDeptId(MyShiroUtils.getDeptId());
        dangerInspect.setCreateUserId(MyShiroUtils.getSessionUserId());
        dangerInspectMapper.insertSelective(dangerInspect);
        if (CollectionUtil.isNotEmpty(dangerInspect.getDangerInspectLists())) {
            dangerInspect.getDangerInspectLists().forEach(inspectList -> {
                inspectList.setInspectId(dangerInspect.getId());
                inspectList.setCompanyId(MyShiroUtils.getCompanyId());
                inspectList.setCreateUserId(MyShiroUtils.getSessionUserId());
                inspectList.setCreateTime(new Date());
            });
            dangerInspectListMapper.insertList(dangerInspect.getDangerInspectLists());
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getImportLabelIds())) {
            List<SafeDangerInspectLabel> safeDangerInspectLabels = new ArrayList<>();
            for (int i = 0; i < dangerInspect.getImportLabelIds().size(); i++) {
                String label = dangerInspectTableLabelMapper
                        .findNameById(dangerInspect.getImportLabelIds().get(i));
                if (ObjectUtil.isNotNull(label)) {
                    SafeDangerInspectLabel safeDangerInspectLabel = new SafeDangerInspectLabel();
                    safeDangerInspectLabel.setLevel(i + 1);
                    safeDangerInspectLabel.setLabel(label);
                    safeDangerInspectLabel.setInspectId(dangerInspect.getId());
                    safeDangerInspectLabels.add(safeDangerInspectLabel);
                }
            }
            safeDangerInspectLabelMapper.insertList(safeDangerInspectLabels);
            dangerInspect.setSafeDangerInspectLabels(safeDangerInspectLabels);
        }
        result.setData(dangerInspect);
        return result;
    }


    public Result importDangerInspectWord(File file,DangerInspect dangerInspect) throws IOException{
        Result result = new Result();
        if(file.getName().endsWith("doc")){
            dangerInspect.setName(file.getName().trim().replace(".doc",""));
            readDoc(file,dangerInspect);
        }else if(file.getName().endsWith("docx")){
            dangerInspect.setName(file.getName().trim().replace(".docx",""));
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getImportLabelIds())) {
            dangerInspect.setTableLabelId(dangerInspect.getImportLabelIds()
                    .get(dangerInspect.getImportLabelIds().size() - 1));
        }
        dangerInspect.setCompanyId(MyShiroUtils.getCompanyId());
        dangerInspect.setCreateTime(new Date());
        dangerInspect.setDeptId(MyShiroUtils.getDeptId());
        dangerInspect.setCreateUserId(MyShiroUtils.getSessionUserId());
        dangerInspectMapper.insertSelective(dangerInspect);

        if (CollectionUtil.isNotEmpty(dangerInspect.getDangerInspectLists())) {
            dangerInspect.getDangerInspectLists().forEach(inspectList -> {
                inspectList.setInspectId(dangerInspect.getId());
                inspectList.setCompanyId(MyShiroUtils.getCompanyId());
                inspectList.setCreateUserId(MyShiroUtils.getSessionUserId());
                inspectList.setCreateTime(new Date());
            });
            dangerInspectListMapper.insertList(dangerInspect.getDangerInspectLists());
        }
        if (CollectionUtil.isNotEmpty(dangerInspect.getImportLabelIds())) {
            List<SafeDangerInspectLabel> safeDangerInspectLabels = new ArrayList<>();
            for (int i = 0; i < dangerInspect.getImportLabelIds().size(); i++) {
                String label = dangerInspectTableLabelMapper
                        .findNameById(dangerInspect.getImportLabelIds().get(i));
                if (ObjectUtil.isNotNull(label)) {
                    SafeDangerInspectLabel safeDangerInspectLabel = new SafeDangerInspectLabel();
                    safeDangerInspectLabel.setLevel(i + 1);
                    safeDangerInspectLabel.setLabel(label);
                    safeDangerInspectLabel.setInspectId(dangerInspect.getId());
                    safeDangerInspectLabels.add(safeDangerInspectLabel);
                }
            }
            safeDangerInspectLabelMapper.insertList(safeDangerInspectLabels);
            dangerInspect.setSafeDangerInspectLabels(safeDangerInspectLabels);
        }
        result.setData(dangerInspect);
        return result;
    }

    public static void main(String[] args) {
        File file=new File("/Users/guqianbin/nbjtjc/uploadFile/safe/2020/12/4/附件2－1：宁波市安全生产标准化达标企业“回头看”检查表（一般工业企业）.doc");
        try {
            readDoc(file,new DangerInspect());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void readDoc(File docFile,DangerInspect dangerInspect) throws IOException{
        FileInputStream in = new FileInputStream(docFile);
        POIFSFileSystem pfs = new POIFSFileSystem(in);
        HWPFDocument hwpf = new HWPFDocument(pfs);
        Range range = hwpf.getRange();//得到文档的读取范围
        TableIterator it = new TableIterator(range);
        List<DangerInspectList> inspectListArrayList=new ArrayList<>();
        int projectCount=0;
        //迭代文档中的表格
        while (it.hasNext()) {
            Table tb = (Table) it.next();
            //迭代行，默认从0开始
            String inspectProject="";
            for (int i = 1; i < tb.numRows(); i++) {
                TableRow tr = tb.getRow(i);
                DangerInspectList inspectList=new DangerInspectList();
                String cellStr=tr.getCell(1).getParagraph(0).text().trim();
                if(StringUtils.isNotEmpty(cellStr)){
                    inspectProject=tr.getCell(1).getParagraph(0).text().trim();
                    projectCount++;
                }
                inspectList.setInspectProject(inspectProject);
                inspectList.setInspectContent(tr.getCell(2).getParagraph(0).text().trim());
                inspectList.setInspectProjectOrder(projectCount);
                inspectList.setNum(i);
                inspectListArrayList.add(inspectList);
//                //迭代列，默认从0开始
//                String rowStr="";
//                for (int j = 0; j < tr.numCells(); j++) {
//                    TableCell td = tr.getCell(j);//取得单元格
//                    //取得单元格的内容
//                    for(int k=0;k<td.numParagraphs();k++){
//                        Paragraph para =td.getParagraph(k);
//                        String s = para.text();
//                        rowStr+="["+s+"]";
//                    } //end for
//                }   //end for
//                System.out.println(tr.numCells()+"-"+rowStr);

            }   //end for
        } //end while
        inspectListArrayList.forEach(dangerInspectList -> {
            System.out.println(dangerInspectList.toString());
        });
        dangerInspect.setDangerInspectLists(inspectListArrayList);
    }

    private void readDocx(File docxFile,DangerInspect dangerInspect)throws IOException{

    }

    private void readXls(File excelFile, DangerInspect dangerInspect) throws IOException {
        InputStream is = new FileInputStream(excelFile);
        // HSSFWorkbook 标识整个excel
        HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);

        int size = hssfWorkbook.getNumberOfSheets();
        List<DangerInspectList> dangerInspectLists = new ArrayList<>();
        // 循环每一页，并处理当前循环页
        for (int numSheet = 0; numSheet < size; numSheet++) {
            // HSSFSheet 标识某一页
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            HSSFRow inspectNameRow = hssfSheet.getRow(0);
            dangerInspect.setName(inspectNameRow.getCell(1).getStringCellValue());
            // 处理当前页，循环读取每一行
            for (int rowNum = 3; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                // HSSFRow表示行
                HSSFRow hssfRow = hssfSheet.getRow(rowNum);
                // 遍历改行，获取处理每个cell元素
                DangerInspectList inspectList = new DangerInspectList();
                HSSFCell cell = hssfRow.getCell(0);
                if (cell == null) {
                    break;
                }
                inspectList.setInspectProject(cell.getStringCellValue());
                cell = hssfRow.getCell(2);
                inspectList.setInspectContent(cell.getStringCellValue());
                dangerInspectLists.add(inspectList);
            }
        }
        dangerInspect.setDangerInspectLists(dangerInspectLists);
    }

    private void readXlsx(File excelFile, DangerInspect dangerInspect) throws IOException {
        InputStream is = new FileInputStream(excelFile);
        // HSSFWorkbook 标识整个excel
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);

        int size = xssfWorkbook.getNumberOfSheets();
        Set<String> labelRelation = new HashSet<>();
        List<DangerInspectList> dangerInspectLists = new ArrayList<>();
        // 循环每一页，并处理当前循环页
        for (int numSheet = 0; numSheet < size; numSheet++) {
            // HSSFSheet 标识某一页
            XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
            if (xssfSheet == null) {
                continue;
            }
            List<SafeKnowledge> safeKnowledges = new ArrayList<>();

            // 处理当前页，循环读取每一行
            for (int rowNum = 3; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(xssfSheet.getSheetName());
                // HSSFRow表示行
                XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                DangerInspectList inspectList = new DangerInspectList();
                XSSFCell cell = xssfRow.getCell(0);
                if (cell == null) {
                    break;
                }
                inspectList.setInspectProject(cell.getStringCellValue());
                cell = xssfRow.getCell(2);
                inspectList.setInspectContent(cell.getStringCellValue());
                dangerInspectLists.add(inspectList);
            }
        }
        dangerInspect.setDangerInspectLists(dangerInspectLists);
    }

    /**
     * 根据传递的标签，组成多个路径进行查询，只支持单条路径
     *
     * @param label
     * @return
     */
    private PageInfo searchByLabels(SafeDangerInspectLabel label, String filterSql) {
        HashMap<Integer, Integer> dangerInspectMap = new HashMap<>();
        List<SafeDangerInspectLabel> safeDangerInspectLabels =
                safeDangerInspectLabelMapper.search(label, null);
        if (CollectionUtil.isEmpty(safeDangerInspectLabels)) {
            return new PageInfo<>(new ArrayList<DangerInspect>());
        }
        safeDangerInspectLabels.forEach(safeDangerInspectLabel -> {
            if (dangerInspectMap.containsKey(safeDangerInspectLabel.getInspectId())) {
                dangerInspectMap.put(safeDangerInspectLabel.getInspectId()
                        , dangerInspectMap.get(safeDangerInspectLabel.getInspectId()) + 1);
            } else {
                dangerInspectMap.put(safeDangerInspectLabel.getInspectId(), 1);
            }
        });
        List<Integer> validatorInspectIds = new ArrayList<>();
        dangerInspectMap.entrySet().forEach(entry -> {
            if (entry.getValue().equals(label.getLabels().size())) {
                validatorInspectIds.add(entry.getKey());
            }
        });
        if (CollectionUtil.isEmpty(validatorInspectIds)) {
            return new PageInfo<>(new ArrayList<DangerInspect>());
        }
        PageHelper.startPage(label.getPageCurrent(), label.getPageSize());
        List<DangerInspect> dangerInspects = dangerInspectMapper.search(label.getDangerInspect()
                , validatorInspectIds, filterSql);
        return new PageInfo<>(dangerInspects);
    }

    /**
     * 根据传递的标签，组成多个路径进行查询，支持多路径进行查询
     *
     * @param label
     * @return
     */
    private PageInfo searchByLabelsByLabelRoute(SafeDangerInspectLabel label) {
        HashMap<Integer, List<DangerInspectTableLabel>> inspectLabelMap = new HashMap<>();
        List<SafeDangerInspectLabel> safeDangerInspectLabels =
                safeDangerInspectLabelMapper.search(label, null);
        if (CollectionUtil.isEmpty(safeDangerInspectLabels)) {
            return new PageInfo<>(new ArrayList<DangerInspect>());
        }
        return new PageInfo();
    }

    public Result addLabel(List<Integer> dangerInspectIds, List<String> labels) {
        Result result = new Result();
        if (CollectionUtil.isEmpty(dangerInspectIds) || CollectionUtil.isEmpty(labels)) {
            result.setFalse("不能为空");
            return result;
        }
        List<SafeDangerInspectLabel> need2AddLabel = new ArrayList<>();
        List<SafeDangerInspectLabel> safeDangerInspectLabels = safeDangerInspectLabelMapper
                .search(null, dangerInspectIds);
        HashMap<Integer, HashSet<String>> addLabels = new HashMap<>();
        if (CollectionUtil.isEmpty(safeDangerInspectLabels)) {
            dangerInspectIds.forEach(id -> {
                for (int i = 0; i < labels.size(); i++) {
                    need2AddLabel.add(new SafeDangerInspectLabel(id, labels.get(i)));
                }
            });
        } else {
            safeDangerInspectLabels.forEach(label -> {
                if (addLabels.containsKey(label.getInspectId())) {
                    addLabels.get(label.getInspectId()).add(label.getLabel());
                } else {
                    HashSet<String> addedLabels = new HashSet<>();
                    addedLabels.add(label.getLabel());
                }
            });
        }
        addLabels.entrySet().forEach(entry -> {
            labels.forEach(diLabel -> {
                if (!entry.getValue().contains(diLabel)) {
                    need2AddLabel.add(new SafeDangerInspectLabel(entry.getKey(), diLabel));
                }
            });
        });
        return result;
    }

    private void insertInspectList(DangerInspect dangerInspect) {
        for(int i=0;i<dangerInspect.getDangerInspectLists().size();i++){
            DangerInspectList dangerInspectList=dangerInspect.getDangerInspectLists().get(i);
            dangerInspectList.setInspectId(dangerInspect.getId());
            dangerInspectList.setCreateUserId(dangerInspect.getCreateUserId());
            dangerInspectList.setCreateTime(new Date());
            dangerInspectList.setInspectProjectOrder(i+1);
        }

        dangerInspectListMapper.insertList(dangerInspect.getDangerInspectLists());
    }

    private void insertInspectLabels(DangerInspect dangerInspect) {
        dangerInspect.getSafeDangerInspectLabels().forEach(safeDangerInspectLabel -> {
            safeDangerInspectLabel.setInspectId(dangerInspect.getId());
        });
        safeDangerInspectLabelMapper.insertList(dangerInspect.getSafeDangerInspectLabels());
    }


    private void copyTableList(DangerInspect fromTable, DangerInspect toTable, int companyId) {
        if (CollectionUtil.isNotEmpty(fromTable.getDangerInspectLists())) {
            fromTable.getDangerInspectLists().forEach(tableList -> {
                DangerInspectList dangerInspectList = new DangerInspectList();
                dangerInspectList.setCreateTime(new Date());
                dangerInspectList.setCreateUserId(MyShiroUtils.getSessionUserId());
                dangerInspectList.setInspectProject(tableList.getInspectProject());
                dangerInspectList.setInspectContent(tableList.getInspectContent());
                dangerInspectList.setCompanyId(companyId);
                toTable.getDangerInspectLists().add(dangerInspectList);
            });
        }
    }

    /**
     * 根据检查表内的检查项，一次性插入所有检查项
     *
     * @param dangerInspects
     */
    private void insertTableList(List<DangerInspect> dangerInspects) {
        List<DangerInspectList> dangerInspectLists = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(dangerInspects)) {
            dangerInspects.forEach(dangerInspect -> {
                dangerInspect.getDangerInspectLists().parallelStream().forEach(dangerInspectList -> {
                    dangerInspectList.setInspectId(dangerInspect.getId());
                });
                dangerInspectLists.addAll(dangerInspect.getDangerInspectLists());
            });
        }
        if (CollectionUtils.isNotEmpty(dangerInspectLists)) {
            dangerInspectListMapper.insertList(dangerInspectLists);
        }
    }

    /**
     * 复制标签
     *
     * @param fromTables 需要被复制标签的表
     * @param toTables   将标签复制到这些表
     */
    private void copyTableLabels(List<DangerInspect> fromTables, List<DangerInspect> toTables) {
        if (CollectionUtil.isEmpty(fromTables)) {
            return;
        }
        List<SafeDangerInspectLabel> insertLabels = new ArrayList<>();
        List<Integer> fromTableIds = fromTables.stream()
                .map(DangerInspect::getId).collect(Collectors.toList());
        List<SafeDangerInspectLabel> labels = safeDangerInspectLabelMapper
                .search(null, fromTableIds);
        Map<Integer, DangerInspect> fromTablesMap = fromTables.stream()
                .collect(Collectors.toMap(DangerInspect::getId, danger -> danger));
//        labels.forEach(label -> {
//            fromTablesMap.get(label.getInspectId()).getSafeDangerInspectLabels().add(label);
//        });
        toTables.parallelStream().forEach(toTable -> {
            List<SafeDangerInspectLabel> fromlabels = fromTablesMap.get(toTable.getFromTableId()).getSafeDangerInspectLabels();
            fromlabels.forEach(fromlabel -> {
                SafeDangerInspectLabel safeDangerInspectLabel = new SafeDangerInspectLabel();
                safeDangerInspectLabel.setInspectId(toTable.getId());
                safeDangerInspectLabel.setLabel(fromlabel.getLabel());
                safeDangerInspectLabel.setLevel(fromlabel.getLevel());
                insertLabels.add(safeDangerInspectLabel);
            });
        });
        safeDangerInspectLabelMapper.insertList(insertLabels);
    }
}
